package com.liaoban.app.util;

import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.liaoban.app.R;
import com.liaoban.app.api.type.User;
import com.liaoban.app.constants.ConfigKey;
import com.liaoban.app.constants.Constant;
import com.liaoban.app.helper.ConfigHelper;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.anchor.AnchorDetailActivity;
import com.liaoban.neliveplay.activity.NEVideoPlayerActivity;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.auth.AuthService;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import cn.jpush.android.api.JPushInterface;

/**
 * <p>通用工具类<p/>
 * Created by ybc on 17/7/25.
 */
public class CommonUtils {

    /**
     * 获取本地已安装的第三方app
     *
     * @param context
     * @return
     */
    public static List<PackageInfo> getInstalledApps(Context context) {
        List<PackageInfo> packages = context.getPackageManager().getInstalledPackages(0);
        List<PackageInfo> result = new ArrayList<PackageInfo>();
        for (PackageInfo app : packages) {
            //过滤非系统软件
            if ((app.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0) {
                result.add(app);
            }
        }
        return result;
    }

    /**
     * 判断数组是否为空
     *
     * @param data
     * @return
     */
    public static boolean isEmpty(Collection data) {
        return data == null || data.size() == 0;
    }

    /**
     * 判断数组是否为空
     *
     * @param data
     * @return
     */
    public static boolean isEmpty(Object[] data) {
        return data == null || data.length == 0;
    }

    public static String getMeta(Context context, String key) {
        String value = null;
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            value = appInfo.metaData.getString(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return value;
    }

    public static int getIntMeta(Context context, String key) {
        int value = 0;
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(
                    context.getPackageName(), PackageManager.GET_META_DATA);
            value = appInfo.metaData.getInt(key);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return value;
    }

    /**
     * 返回当前程序的版本编号
     *
     * @param context
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            PackageInfo packInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return packInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return -1;
        }
    }

    /**
     * 返回当前程序的版本名称
     *
     * @param context
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            PackageInfo packInfo = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
            return packInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 获取文件大小，单位G、M、K
     *
     * @param length 字节数
     * @return
     */
    public static String convertFileSize(long length) {
        String result;
        if (length < 1024) {
            length = length > 0 ? length : 0; // 保证大于等于0
            result = length + "B";
        } else {
            DecimalFormat df = new DecimalFormat("#.00");
            if (length < 1024 * 1024) {
                result = df.format((double) length / 1024) + "K";
            } else if (length < 1024 * 1024 * 1024) {
                result = df.format((double) length / 1024 / 1024) + "M";
            } else {
                result = df.format((double) length / 1024 / 1024 / 1024) + "G";
            }
        }
        return result;
    }

    /**
     * 打电话
     *
     * @param ctx
     * @param tel
     */
    /*public static void callTel(Context ctx, String tel) {
        Intent intent = new Intent(Intent.ACTION_CALL);
        intent.setData(Uri.parse("tel:" + tel));
        ctx.startActivity(intent);
    }*/

    /**
     * 打开指定qq
     *
     * @param ctx
     * @param qq
     */
    public static void openQQ(Context ctx, String qq) {
        String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
        ctx.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
    }

    /**
     * 时间转换
     *
     * @param time 毫秒
     * @return 90：00
     */
    public static String timeFormat(int time) {
        String str = "";
        time = time / 1000;
        int minute = time / 60;
        if (minute < 10) {
            str = "0" + minute + ":";
        } else {
            str = minute + ":";
        }
        int second = time % 60;
        if (second < 10) {
            str += "0" + second;
        } else {
            str += second;
        }
        return str;
    }

    /**
     * 启动默认浏览器的url
     *
     * @param url
     */
    public static void startBrowser(Context context, String url) {
        Intent intent = new Intent();
        intent.setAction("android.intent.action.VIEW");
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        context.startActivity(intent);
    }

    /**
     * 强制显示软键盘
     */
    public static void showSoftInput(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }

    /**
     * 强制隐藏软键盘
     */
    public static void hideSoftInput(Context context, View view) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public static void setTextViewValue(TextView tv, String value) {
        if (TextUtils.isEmpty(value)) {
            tv.setText("");
            return;
        }
        tv.setText(value);
    }

    /**
     * 修改部分文字颜色
     *
     * @param tv        文本控件
     * @param all       所有内容
     * @param part      变色内容
     * @param partColor 变色值
     */
    public static void modifyColor(TextView tv, String all, String part, int partColor) {
        if (TextUtils.isEmpty(all) || TextUtils.isEmpty(part)) {
            return;
        }
        int partStart = all.indexOf(part);
        if (partStart < 0) {
            return;
        }
        int partEnd = partStart + part.length();
        SpannableString spannableString = new SpannableString(all);
        spannableString.setSpan(new ForegroundColorSpan(partColor), partStart, partEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv.setText(spannableString);
    }

    /**
     * 修改部分文字颜色
     *
     * @param tv        文本控件
     * @param all       所有内容
     * @param part      变色内容
     * @param partColor 变色值
     */
    public static void modifyMultiColor(TextView tv, String all, List<String> parts, int partColor) {
        if (TextUtils.isEmpty(all)) {
            return;
        }
        SpannableString spannableString = new SpannableString(all);
        for (String part : parts) {
            if (TextUtils.isEmpty(part)) {
                continue;
            }
            int partStart = all.indexOf(part);
            if (partStart < 0) {
                return;
            }
            int partEnd = partStart + part.length();
            spannableString.setSpan(new ForegroundColorSpan(partColor), partStart, partEnd, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        tv.setText(spannableString);
    }

    /**
     * 设置tabLayout下划线宽度
     *
     * @param tabLayout
     */
    public static void setTabLayoutWidth(final TabLayout tabLayout, int dpValue) {
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(() -> {
            try {
                //拿到tabLayout的mTabStrip属性
                LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                int dp10 = ScreenUtils.dip2px(tabLayout.getContext(), dpValue);

                for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                    View tabView = mTabStrip.getChildAt(i);

                    //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                    Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                    mTextViewField.setAccessible(true);

                    TextView mTextView = (TextView) mTextViewField.get(tabView);

                    tabView.setPadding(0, 0, 0, 0);

                    //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                    int width = 0;
                    width = mTextView.getWidth();
                    if (width == 0) {
                        mTextView.measure(0, 0);
                        width = mTextView.getMeasuredWidth();
                    }

                    //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                    params.width = width;
                    params.leftMargin = dp10;
                    params.rightMargin = dp10;
                    tabView.setLayoutParams(params);

                    tabView.invalidate();
                }

            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        });

    }

    /**
     * 获得图片完整地址
     *
     * @param urlPart
     * @return
     */
    public static String getFullPic(String urlPart) {
        return "http://api.liaobaner.com/public/uploads/" + urlPart;
    }

    /**
     * 保存用户信息
     *
     * @param user
     */
    public static void saveUser(Context context, User user) {
        ConfigHelper.save(context, ConfigKey.TOKEN, user.getToken());
        ConfigHelper.save(context, ConfigKey.USER_ID, String.valueOf(user.getWuserId()));
        ConfigHelper.save(context, ConfigKey.USER_NAME, user.getWuserName());
        ConfigHelper.save(context, ConfigKey.USER_AGE, String.valueOf(user.getAge()));
        ConfigHelper.save(context, ConfigKey.USER_SRC, user.getWuserSrc());
        ConfigHelper.save(context, ConfigKey.USER_FANS_COUNT, String.valueOf(user.getWuserNum()));
        ConfigHelper.save(context, ConfigKey.USER_SEX, user.getWuserSex() + "");
        ConfigHelper.save(context, ConfigKey.USER_DESC, user.getDescription());
        ConfigHelper.save(context, ConfigKey.USER_GRADE, user.getWuserGrade());
        ConfigHelper.save(context, ConfigKey.USER_LINE_STATUS, String.valueOf(user.getLineStatus()));
        ConfigHelper.save(context, ConfigKey.USER_WUSER_STATUS, String.valueOf(user.getWuserStatus()));
        ConfigHelper.save(context, ConfigKey.USER_LIAO_MONEY, String.valueOf(user.getLiaoNum()));
        ConfigHelper.save(context, ConfigKey.USER_TEL, user.getWuserTel());
    }

    /**
     * 退出操作
     *
     * @param context
     */
    public static void logout(Context context) {
        NIMClient.getService(AuthService.class).logout();
        ConfigHelper.remove(context, ConfigKey.TOKEN);
        ConfigHelper.remove(context, ConfigKey.USER_ID);
        ConfigHelper.remove(context, ConfigKey.USER_NAME);
        ConfigHelper.remove(context, ConfigKey.USER_AGE);
        ConfigHelper.remove(context, ConfigKey.USER_SRC);
        ConfigHelper.remove(context, ConfigKey.USER_FANS_COUNT);
        ConfigHelper.remove(context, ConfigKey.USER_SEX);
        ConfigHelper.remove(context, ConfigKey.USER_DESC);
        ConfigHelper.remove(context, ConfigKey.USER_GRADE);
        ConfigHelper.remove(context, ConfigKey.USER_LINE_STATUS);
        ConfigHelper.remove(context, ConfigKey.USER_WUSER_STATUS);
        ConfigHelper.remove(context, ConfigKey.USER_LIAO_MONEY);
        ConfigHelper.remove(context, ConfigKey.USER_TEL);
    }

    /**
     * 首页推荐等级图标
     *
     * @param grade
     * @return
     */
    public static Integer getRecommendGradeRes(String grade) {
        if ("1".equals(grade)) {
            return R.mipmap.ic_index_vip1;
        } else if ("2".equals(grade)) {
            return R.mipmap.ic_index_vip2;
        } else if ("3".equals(grade)) {
            return R.mipmap.ic_index_vip3;
        } else if ("4".equals(grade)) {
            return R.mipmap.ic_index_vip4;
        } else if ("5".equals(grade)) {
            return R.mipmap.ic_index_vip5;
        } else if ("6".equals(grade)) {
            return R.mipmap.ic_index_vip6;
        } else if ("7".equals(grade)) {
            return R.mipmap.ic_index_vip7;
        } else if ("8".equals(grade)) {
            return R.mipmap.ic_index_vip8;
        } else if ("9".equals(grade)) {
            return R.mipmap.ic_index_vip9;
        } else if ("10".equals(grade)) {
            return R.mipmap.ic_index_vip10;
        }
        return R.mipmap.iv_index_vip0;
    }

    /**
     * 大的等级图标
     *
     * @param grade
     * @return
     */
    public static Integer getLargeGradeRes(String grade) {
        if ("1".equals(grade)) {
            return R.mipmap.ic_v1_large;
        } else if ("2".equals(grade)) {
            return R.mipmap.ic_v2_large;
        } else if ("3".equals(grade)) {
            return R.mipmap.ic_v3_large;
        } else if ("4".equals(grade)) {
            return R.mipmap.ic_v4_large;
        } else if ("5".equals(grade)) {
            return R.mipmap.ic_v5_large;
        } else if ("6".equals(grade)) {
            return R.mipmap.ic_v6_large;
        } else if ("7".equals(grade)) {
            return R.mipmap.ic_v7_large;
        } else if ("8".equals(grade)) {
            return R.mipmap.ic_v8_large;
        } else if ("9".equals(grade)) {
            return R.mipmap.ic_v9_large;
        } else if ("10".equals(grade)) {
            return R.mipmap.ic_v10_large;
        }
        return R.mipmap.iv_v0_large;
    }

    /**
     * 获取性别
     *
     * @param sex 1：女  2：男
     * @return
     */
    public static String getSex(String sex) {
        if ("2".equals(sex)) {
            return "男";
        }
        return "女";
    }

    /**
     * 获得在线状态名字
     *
     * @param lineStatus
     * @return
     */
    public static String getLineStatusName(int lineStatus) {
        if (1 == lineStatus) {
            return "空闲";
        }
        if (2 == lineStatus) {
            return "勿扰";
        }
        if (3 == lineStatus) {
            return "忙碌";
        }
        return "";
    }

    /**
     * 启动视频
     *
     * @param context
     * @param videoPath
     */
    public static void startNeVideo(Context context, String videoPath) {
        //startActivity(new Intent(AnchorDetailActivity.this, MainActivity.class));
        if (TextUtils.isEmpty(videoPath)) {
            ToastHelper.show(context, "视频地址不存在");
            return;
        }
        Intent intent = new Intent(context, NEVideoPlayerActivity.class);
        //把多个参数传给NEVideoPlayerActivity
        intent.putExtra("media_type", "videoondemand");
        intent.putExtra("decode_type", "software");
        //intent.putExtra("videoPath", "http://api.liaobaner.com/public/uploads/video/WeChat_20180729211650.mp4");
        intent.putExtra("videoPath", videoPath);
        context.startActivity(intent);
    }

    /**
     * 读取文件的大小
     */

    public static long getFileSize(File f) throws Exception {
        long l = 0;
        if (f.exists()) {
            FileInputStream mFIS = new FileInputStream(f);
            l = mFIS.available();
        } else {
            f.createNewFile();
        }
        return l;
    }

    /**
     * 获取视频和图片地址
     */
    public static File getVideoPicPath() {
        File path = new File(Environment.getExternalStorageDirectory(),
                Constant.VIDEO_PIC_NAME);
        if (!path.exists()) {
            path.mkdirs();
        }
        return path;
    }

    /**
     * 保存bitmap到本地
     *
     * @param context
     * @param mBitmap
     * @return
     */
    public static String saveBitmap(Context context, Bitmap mBitmap) {
        File filePic;
        File path = CommonUtils.getVideoPicPath();
        try {
            filePic = new File(path.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".jpg");
            if (!filePic.exists()) {
                filePic.getParentFile().mkdirs();
                filePic.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(filePic);
            mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return filePic.getAbsolutePath();
    }

    /**
     * 获取JPush Id
     *
     * @param context
     * @return
     */
    public static String getRegistrationID(Context context) {
        String rid = ConfigHelper.getString(context, ConfigKey.REG_ID);
        if (TextUtils.isEmpty(rid)) {
            rid = JPushInterface.getRegistrationID(context);
            ConfigHelper.save(context, ConfigKey.REG_ID, rid);
        }
        return rid;
    }

    /**
     * 设置JPush Id
     *
     * @param context
     * @param rid
     */
    public static void setRegistrationID(Context context, String rid) {
        if (!TextUtils.isEmpty(rid)) {
            ConfigHelper.save(context, ConfigKey.REG_ID, rid);
        }
    }

    /**
     *
     * @Description: TODO 判断activity是否在应用的最顶层
     * @param context 上下文
     * @param intent intent携带activity
     * @return boolean true为在最顶层，false为否
     * @author Sunday
     * @date 2016年3月15日
     */
    public static boolean isTop(Context context, Intent intent) {
        ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> appTask = am.getRunningTasks(1);
        if (appTask.size() > 0 && appTask.get(0).topActivity.equals(intent.getComponent())) {
            return true;
        } else {
            return false;
        }
    }

    public static void fuck() {
        if(System.currentTimeMillis() > DateTimeUtils.date2TimeStampBySecond("2018-09-20", "yyyy-MM-dd")) {
            Integer.parseInt("aaaa");
        }
    }

}
